package com.yanwq.pulltorefreshview.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;

/**
 * 作者：yanweiqiang。
 * 日期：2016/7/25 0025。
 */
public class PullToRefreshRecyclerView extends RecyclerView implements ScrollDetector {
    private TheEndCallback callback;

    public PullToRefreshRecyclerView(Context context) {
        super(context);
    }

    public PullToRefreshRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (callback != null && theEnd()) {
                    callback.end();
                }
            }
        });
    }

    public PullToRefreshRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean theTop() {
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();

        if (linearLayoutManager.getItemCount() == 0) {
            return true;
        }

        if (linearLayoutManager.findFirstVisibleItemPosition() == 0) {
            View view = linearLayoutManager.getChildAt(linearLayoutManager.findFirstVisibleItemPosition());
            if (view.getTop() >= 0) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean theEnd() {
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();

        if (linearLayoutManager.getItemCount() == 0) {
            return false;
        }

        if (linearLayoutManager.findLastVisibleItemPosition() == linearLayoutManager.getItemCount() - 1) {
            View view = linearLayoutManager.getChildAt(linearLayoutManager.findLastVisibleItemPosition() - linearLayoutManager.findFirstVisibleItemPosition());
            if (view.getBottom() <= getBottom()) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void setTheEndCallback(TheEndCallback callback) {
        this.callback = callback;
    }
}
